import FetchError from '../models/FetchError';
import { Person } from '../models/Persons';

enum HttpMethod {
	GET,
	POST
}

const httpBaseApi = import.meta.env.VITE_API_BASE_URI;

export async function GetUsersAsync(): Promise<Record<string, Person[]>> {
	return callApi(`${httpBaseApi}/users`, HttpMethod.GET);
}

export async function GetUserAsync(userid: string): Promise<Person | undefined> {
	return callApi(`${httpBaseApi}/users/${userid}`, HttpMethod.GET);
}

export async function GetMeAsync(): Promise<Person | undefined> {
	return callApi(`${httpBaseApi}/users/me`, HttpMethod.GET)
}

async function callApi(uri: string, method: HttpMethod): Promise<any> {
	const response = await fetch(uri,
		{
			method: HttpMethod[method],
			credentials: 'include'
		});

	if (!response.ok)
		throw new FetchError(response);

	return await response.json();
}
